import *as R from 'ramda';
import { IO, Future } from 'vendor/ramda-fantasy';
import U from "./index"
const handleRequest = R.curry(({ isShowLoading = true, loading={ that: null, name: null }, isHideLoading = true, isShowSuccessMsg = false, successMsg = '请求成功！', errorMsg = '请求出错！' }, getPromise) => {
  const showLoading = R.ifElse(
    R.isNil,
    () => IO(() => wx.showLoading({ title: '加载中' })),
    () => IO(() => loading.that.setData({ [loading.name]: true }))
  );
  
  const hideLoading = R.ifElse(
    R.isNil,
    () => IO(() => wx.hideLoading()),
    () => IO(() => loading.that.setData({ [loading.name]: false }))
  );
  
  return Future((reject, resolve) => {
    const handleSuccess = res => IO(
      R.compose(
        () => resolve(res),
        () => R.when(
          R.equals(true),
          () => wx.showToast({
            title: successMsg,
            icon: 'none'
          })
        )(isShowSuccessMsg)
      )
    );
  
    const handleError = errorMsg => res => IO(
      R.compose(
        () => reject(res),
        () => wx.showToast({
          title: errorMsg,
          icon: 'none'
        })
      )
    );
    
    const handleError5 = res => R.composeK(
      U.logout,
      handleError(res.msg || errorMsg),
    )(res)
    
    return R.compose(
      R.otherwise(err => R.compose(
        () => handleError('请求出错')(err).runIO(),
        R.when(
          R.equals(true),
          () => hideLoading(loading.that).runIO()
        )
      )(isHideLoading)),
      R.then(res => R.compose(
        () => R.cond([
          [ R.either(R.compose(R.equals(1), R.prop('code')), R.is(Array)), handleSuccess ],
          [ R.compose(R.equals(5), R.prop('code')), handleError5 ],
          [ R.T, handleError(res.msg || errorMsg) ]
        ])(res).runIO(),
        R.when(
          R.equals(true),
          () => hideLoading(loading.that).runIO()
        )
      )(isHideLoading)),
      getPromise,
      R.when(
        R.equals(true),
        () => showLoading(loading.that).runIO()
      )
    )(isShowLoading)
  })
});
export { handleRequest };
